<template>
  <div class="divisionalstatement-wrapper">
    <div class="content">
      <div class="content-left">
        <div class="in_concent_left_1">
          <div
            v-for="(item, index) in tabsData"
            :key="index"
            :class="[
              'in_concent_left_pitch',
              tabIndex == item.key ? 'choose_itch' : '',
            ]"
            @click="handleTabChange(item.key)"
          >
            {{ item.value }}
          </div>
        </div>
      </div>
      <div class="content-right">
        <div class="content-right-wrap">
          <div
            class="orderHeader"
            v-if="tabIndex == 1"
            style="margin: 5px 0px 0px 0px"
          >
            <div class="orderSearch">
              <el-form ref="form" :model="searchParams" :inline="true">
                <el-row>
                  <el-form-item label="所属客户">
                    <el-select
                      placeholder="所属客户"
                      remote
                      filterable
                      clearable
                      :remote-method="searchCustomerList"
                      v-model="searchParams.customer_id"
                    >
                      <el-option
                        v-for="(item, index) in customerPeopleData"
                        :key="index"
                        :value="item.id + ''"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="送货方式">
                    <el-select
                      v-model="searchParams.delivery_method"
                      filterable
                      clearable
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in deliveryMethodData"
                        :key="item.item_code"
                        :label="item.item_name"
                        :value="item.item_code"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="承运类型">
                    <el-select
                      style="width: 195px"
                      clearable
                      v-model="searchParams.waybill_product_type"
                    >
                      <el-option
                        v-for="(type, index) in transportsTypeData"
                        :key="index"
                        :label="type.name"
                        :value="type.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属销售" size="mini">
                    <el-select
                      filterable
                      multiple
                      v-model="searchParams.sale_ids"
                      style="width: 160px"
                    >
                      <el-option
                        v-for="sales in salesList"
                        :key="sales.id"
                        :label="sales.nickname"
                        :value="sales.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-form-item label="时间类型">
                  <el-radio-group
                    @input="handleChangeTimeType"
                    v-model="searchParams.time_type"
                  >
                    <el-radio-button label="0">年</el-radio-button>
                    <el-radio-button label="1">月</el-radio-button>
                    <el-radio-button label="4">周</el-radio-button>
                    <el-radio-button label="2">日</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <div style="display: inline-block; margin-left: 5px">
                  <template v-if="searchParams.time_type === '0'">
                    <el-date-picker
                      key="yearrangeStart"
                      v-model="searchParams.create_time.start_time"
                      type="year"
                      placeholder="选择年度"
                      value-format="yyyy"
                      format="yyyy 年"
                      style="width: 120px"
                    />
                    -
                    <el-date-picker
                      key="yearrangeEnd"
                      v-model="searchParams.create_time.end_time"
                      type="year"
                      placeholder="选择年度"
                      value-format="yyyy"
                      format="yyyy 年"
                      style="width: 120px"
                    />
                  </template>
                  <template v-else-if="searchParams.time_type === '1'">
                    <el-date-picker
                      key="monthrange"
                      v-model="searchParams.monthrange"
                      type="monthrange"
                      placeholder="选择月度"
                      value-format="yyyyMM"
                      start-placeholder="开始月度"
                      end-placeholder="结束月度"
                      format="yyyy 年 MM 月"
                      style="width: 300px"
                      @change="handleDateChange"
                    />
                  </template>
                  <template v-else-if="searchParams.time_type === '2'">
                    <!-- 日期 范围选择 -->
                    <el-date-picker
                      key="daterange"
                      v-model="searchParams.daterange"
                      type="daterange"
                      value-format="yyyyMMdd"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      style="width: 240px"
                      @change="handleDateChange"
                    />
                  </template>
                  <template v-else-if="searchParams.time_type === '4'">
                    <el-date-picker
                      key="weekrangeYearStart"
                      v-model="searchParams.create_time.start_year"
                      type="year"
                      placeholder="年份"
                      editable
                      :clearable="false"
                      value-format="yyyy"
                      format="yyyy 年"
                      style="width: 120px"
                      @change="handleWeekChange"
                    />
                    <el-select
                      key="weekrange1"
                      style="width: 100px"
                      v-model="searchParams.create_time.start_week"
                      filterable
                      clearable
                      placeholder="周"
                      @change="handleWeekChange"
                    >
                      <el-option
                        v-for="item in weeksData"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      >
                      </el-option>
                    </el-select>
                    -
                    <el-date-picker
                      key="weekrangeYearEnd"
                      v-model="searchParams.create_time.end_year"
                      type="year"
                      placeholder="年份"
                      @change="handleWeekChange"
                      editable
                      :clearable="false"
                      value-format="yyyy"
                      format="yyyy 年"
                      style="width: 120px"
                    />
                    <el-select
                      key="weekrange2"
                      @change="handleWeekChange"
                      style="width: 100px"
                      v-model="searchParams.create_time.end_week"
                      filterable
                      clearable
                      placeholder="周"
                    >
                      <el-option
                        v-for="item in weeksData"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </div>
                <el-form-item>
                  <div style="margin-left: 20px">
                    <el-button
                      type="primary"
                      icon="el-icon-search"
                      @click="handleSearch"
                      >查询
                    </el-button>
                    <el-button
                      type="primary"
                      plain
                      icon="el-icon-refresh"
                      @click="handleReset"
                      >重置
                    </el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div
            class="orderHeader"
            v-if="tabIndex == 2"
            style="margin: 5px 0px 0px 0px"
          >
            <div class="orderSearch">
              <el-form ref="form" :model="searchParams" :inline="true">
                <el-row>
                  <el-form-item label="所属客户">
                    <el-select
                      placeholder="所属客户"
                      remote
                      filterable
                      clearable
                      :remote-method="searchCustomerList"
                      v-model="searchParams.customer_id"
                    >
                      <el-option
                        v-for="(item, index) in customerPeopleData"
                        :key="index"
                        :value="item.id + ''"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属销售" size="mini">
                    <el-select
                      filterable
                      multiple
                      v-model="searchParams.sale_ids"
                      style="width: 160px"
                    >
                      <el-option
                        v-for="sales in salesList"
                        :key="sales.id"
                        :label="sales.nickname"
                        :value="sales.id"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <div style="margin-left: 20px">
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="handleSearch"
                        >查询
                      </el-button>
                      <el-button
                        type="primary"
                        plain
                        icon="el-icon-refresh"
                        @click="handleReset"
                        >重置
                      </el-button>
                    </div>
                  </el-form-item>
                </el-row>
              </el-form>
            </div>
          </div>
          <ReportTable_divisona
            ref="table_key"
            :tableKey="tabIndex"
            :key="tabIndex"
            :currentParam="currentParam"
            @export="handleClickExport"
          ></ReportTable_divisona>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  AnalysisCustomerExport,
  AnalysisCustomerLossExport,
} from "@/api/report";
import {
  AdminBox, //所属销售
} from "@/api/customer";
import { customerPeople } from "@/api/information";
import { dictionanryList } from "@/page/material/common/common";
import { getTransportsList } from "@/api/waybill";
import ReportTable_divisona from "./components/ReportTable_divisona.vue";
import moment from "moment";
moment.locale("zh-cn");
export default {
  name: "operatereport",
  components: { ReportTable_divisona },
  props: [],
  data() {
    return {
      tabsData: [
        {
          key: "1",
          value: "客户收入统计",
        },
        {
          key: "2",
          value: "流失客户预警",
        },
      ],
      tabIndex: "",
      searchParams: {
        customer_id: "",
        delivery_method: "",
        waybill_product_type: "",
        time_type: "",
        create_time: {
          start_time: "",
          end_time: "",
          start_year: "",
          start_week: "",
          end_year: "",
          end_week: "",
        },
        // sales_id: [],
        daterange: [],
        monthrange: [],
        sale_ids: [],
        // sales_ids: [],//流失客户预警
      },

      customerPeopleData: [],
      deliveryMethodData: [],
      transportsTypeData: [],
      weeksData: [],
      chartKeys: [], //表格key的合集
      loading: false,
      tableData: [],
      headerData: [],
      currentTabData: {},
      currentParam: {},
      itemkey: "",
      salesList: [], //所属销售
    };
  },
  computed: {},
  mounted() {
    this.initSearchTime();
    this.getSalesList(); //所属销售
    // CustomChartOption({}).then(res => {
    //     this.tabsData = res.data.data;
    //     this.handleTabChange(this.tabsData[0].key);
    // });
    this.CustomChartOption();
    dictionanryList(["delivery_method"]).then((res) => {
      this.deliveryMethodData = res.data.list["delivery_method"];
    });
    getTransportsList({ is_all: false }).then((res) => {
      this.transportsTypeData = res.data.data;
    });
    for (let i = 1; i < 54; i++) {
      this.weeksData.push({
        key: i < 10 ? "0" + i : i + "",
        value: `第${i}周`,
      });
    }
  },
  methods: {
    handleClickExport(key) {
      const params = this.getSearchParams();
      if (this.tabIndex == 1) {
        AnalysisCustomerExport({
          ...params,
        }).then((res) => {
          this.reqUrl = "https://" + res.data.loaded_url;
          window.open(this.reqUrl);
        });
      } else if (this.tabIndex == 2) {
        AnalysisCustomerLossExport({
          ...params,
        }).then((res) => {
          this.reqUrl = "https://" + res.data.loaded_url;
          window.open(this.reqUrl);
        });
      }
      // CustomSubChartExport({
      //     id: key,
      //     ...params
      // }).then(res => {
      //     this.reqUrl = "https://" + res.data.loaded_url;
      //     window.open(this.reqUrl);
      // });
    },
    // 默认当日
    initSearchTime() {
      this.searchParams.time_type = "2";

      const today = moment().format("YYYYMMDD");
      const day7ago = moment().subtract(1, "days").format("YYYYMMDD");
      this.searchParams.create_time.start_time = day7ago;
      this.searchParams.create_time.end_time = today;
      this.searchParams.daterange = [day7ago, today];
    },
    handleChangeTimeType(val) {
      // this.$set(this.searchParams, 'monthrange', []);
      // this.$set(this.searchParams, 'daterange', []);
      // this.$set(this.searchParams, 'create_time', {
      //     start_time: "",
      //     end_time: "",
      //     start_year: "",
      //     start_week: "",
      //     end_year: "",
      //     end_week: "",
      // });
      Object.assign(
        this.$data.searchParams.monthrange,
        this.$options.data().searchParams.monthrange
      );
      Object.assign(
        this.$data.searchParams.daterange,
        this.$options.data().searchParams.daterange
      );
      Object.assign(
        this.$data.searchParams.create_time,
        this.$options.data().searchParams.create_time
      );

      if (this.searchParams.time_type == "0") {
        const nowYear = moment().format("YYYY");
        this.searchParams.create_time.start_time = nowYear;
        this.searchParams.create_time.end_time = nowYear;
      } else if (this.searchParams.time_type == "1") {
        const nowMonth = moment().format("YYYYMM");
        this.searchParams.create_time.start_time = nowMonth;
        this.searchParams.create_time.end_time = nowMonth;
        this.$data.searchParams.monthrange = [nowMonth, nowMonth];
      } else if (this.searchParams.time_type == "2") {
        this.initSearchTime();
      }
      if (this.searchParams.time_type == "3") {
        this.$set(this.searchParams.create_time, "start_year", "2023");
        this.$set(this.searchParams.create_time, "start_week", "");
        this.$set(this.searchParams.create_time, "end_year", "2023");
        this.$set(this.searchParams.create_time, "end_week", "");
      }
    },
    handleSearch() {
      this.getCharts();
      // console.log(this.searchParams, "this.currentParam查询");
      this.$refs.table_key.initList(this.searchParams); // 方法1:触发监听事件
    },
    handleReset() {
      Object.assign(this.$data.searchParams, this.$options.data().searchParams);
      this.initSearchTime();
      // this.getCharts();
      this.$refs.table_key.initList(this.searchParams); // 方法1:触发监听事件
    },

    handleWeekChange(val) {
      this.searchParams.create_time.start_time =
        this.searchParams.create_time.start_year +
        this.searchParams.create_time.start_week;
      this.searchParams.create_time.end_time =
        this.searchParams.create_time.end_year +
        this.searchParams.create_time.end_week;
    },
    handleDateChange(val) {
      if (val) {
        this.searchParams.create_time.start_time = val[0];
        this.searchParams.create_time.end_time = val[1];
      } else {
        this.searchParams.create_time.start_time = "";
        this.searchParams.create_time.end_time = "";
      }
    },
    handleSelectionChange() {},
    handleTabChange(val) {
      this.tabIndex = val;
      this.currentTabData =
        this.tabsData.find((item) => item.key === val) || {};
      this.chartKeys = [this.currentTabData];
      // this.currentParam = this.getSearchParams();
      this.getCharts();
      // CustomSubChartOption({
      //     custom_chart_id: val
      // }).then(res => {
      //     const data = res.data.data;
      //     this.chartKeys = data;
      //     this.getCharts();
      // });
    },
    getSearchParams() {
      const isTypeReqiured = (this.currentTabData.search || []).includes(
        "waybill_product_type"
      );
      if (isTypeReqiured && !this.searchParams.waybill_product_type) {
        this.searchParams.waybill_product_type = this.transportsTypeData[0].id;
      }
      return {
        ...this.searchParams,
        create_time: {
          start_time: this.searchParams.create_time.start_time,
          end_time: this.searchParams.create_time.end_time,
        },
        daterange: undefined,
        monthrange: undefined,
      };
    },

    getCharts() {
      this.currentParam = this.getSearchParams();

      // const key = `table_${item.key}`;
      // this.$refs.table_1.$emit('getCharts','发送给方法一的数据')
      // this.$refs.table_1.getCharts() // 方法1:触发监听事件
      // this.$nextTick(() => {

      // });
    },
    //获取所属客户
    searchCustomerList(query) {
      //获取客户
      if (query !== "") {
        setTimeout(async () => {
          // let { router, router_id } = this.formData;
          let result = await customerPeople({
            name: query, // 名称
            id: "",
            is_send: "1",
            is_receive: "",
          });
          if (result.data.length > 0) {
            this.customerPeopleData = result.data;
          } else {
            this.customerPeopleData = [];
          }
        }, 200);
      } else {
        this.customerPeopleData = [];
      }
    },
    // 侧边的列表
    CustomChartOption() {
      const index = this.$route.query.key || this.tabsData[0].key;
      this.handleTabChange(index);
    },
    async getSalesList() {
      let result = await AdminBox({
        user_type: "0",
      });
      // console.log("所属销售函数调用", result);
      this.salesList = result.data || [];
    },
  },
};
</script>
<style lang="scss" scoped>
.divisionalstatement-wrapper {
  background: #fff;
  padding: 10px 0px;
  /* min-height: 100vh; */
  /* height: calc(100vh); */
  .orderHeader {
    margin-top: 5px;
    background-color: #fff;

    .orderSearch {
      form {
        ::v-deep .el-form-item__label {
          font-size: 14px;
        }

        .el-textarea {
          width: 135px;
        }
      }
    }
  }

  .content {
    display: flex;
    width: 100%;

    .in_concent_left_1 {
      border-right: 1px solid #ededed;
      height: 100%;

      .in_concent_left_pitch {
        width: 180px;
        height: 40px;
        line-height: 40px;
        padding-left: 20px;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .in_concent_left_pitch:hover {
        height: 40px;
        width: 180px;
        background: #e6f7ff;
        line-height: 40px;
        padding-left: 20px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .choose_itch {
        height: 40px;
        width: 180px;
        background: #e6f7ff;
        line-height: 40px;
        padding-left: 20px;
        color: #2798ff;
        border-right: 4px solid #1890ff;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .content-left {
      flex: 0 0 210px;
    }

    .content-right {
      width: calc(100% - 210px);
      .content-right-wrap {
        padding: 0 20px;
        width: 100%;
        box-sizing: border-box;
      }
    }
  }
}
</style>